import {Form, message, Radio} from "antd";
import React, {useEffect, useState} from "react";
import {dictDetail} from "../../api";
import {AxiosResponse} from "axios/index";
import {useLocation} from "react-router-dom";
import {ArticleDataType, LiteratureDataType} from "../../util/publicType";

interface Props {
    id: string,
    detailData: LiteratureDataType | ArticleDataType | null,
    spanValue?: number
}

// 编辑表单分类封装
const CategoryForm = React.memo(({id, detailData, spanValue = 5}: Props) => {
    // 路由信息
    const l = useLocation();
    // 判断是否为更新页
    const isUpdate = l.pathname.indexOf("update") >= 0;
    // 分类数据
    const [category, setCategory] = useState<Array<{ id: string, name: string }>>([]);

    // data变化时，判断是否拿到数据字典分类id，拿到即执行
    useEffect(() => {
        // 如果为更新页面，在详情拿id，并监听detailData变化，进行请求
        //如果是新增页面，直接判断，然后拿地址里面的id请求渲染
        if (detailData || !isUpdate) {
            dictDetail(isUpdate ? (detailData?.dict?.type_id as string) : (id as string)).then((r: AxiosResponse) => {
                const {data} = r.data.data;
                setCategory(data);
            }, err => message.error(err))
        }
    }, [detailData]);

    return (
        <Form.Item
            labelCol={{span: spanValue}}
            label="类型"
            name="category_id"
            rules={[{required: true, message: '至少选择一项'}]}
        >
            <Radio.Group>
                {
                    category.map(v => {
                        return (
                            <Radio key={v.id} value={v.id}>{v.name}</Radio>
                        )
                    })
                }
            </Radio.Group>
        </Form.Item>
    )
})

export default CategoryForm;